<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\translation;

use app\adminapi\controller\Base;
use app\common\model\TranslateApi as TranslateApiModel;
use app\service\translation\TranslateApiService;

/**
 * 翻译API管理控制器
 */
class TranslateApi extends Base
{
    /**
     * @notes 获取API列表
     * @auth true
     */
    public function getList()
    {
        $list = TranslateApiModel::order('priority', 'asc')->select();
        $this->success('', $list);
    }

    /**
     * @notes 获取API详情
     * @auth true
     */
    public function getDetail()
    {
        $id  = inputs('id/d', 0);
        $api = TranslateApiModel::find($id);

        if (!$api) {
            $this->error('API配置不存在');
        }

        $this->success('', $api);
    }

    /**
     * @notes 添加API配置
     * @auth true
     */
    public function addApi()
    {
        $data = [
            'name'        => inputs('name/s', ''),
            'provider'    => inputs('provider/s', ''),
            'api_key'     => inputs('api_key/s', ''),
            'api_secret'  => inputs('api_secret/s', ''),
            'endpoint'    => inputs('endpoint/s', ''),
            'priority'    => inputs('priority/d', 0),
            'daily_limit' => inputs('daily_limit/d', 0),
            'config'      => inputs('config/a', []),
        ];

        if (!$data['name'] || !$data['provider'] || !$data['api_key']) {
            $this->error('参数不完整');
        }

        $api = new TranslateApiModel();
        $api->save($data);

        $this->success('添加成功');
    }

    /**
     * @notes 编辑API配置
     * @auth true
     */
    public function editApi()
    {
        $id   = inputs('id/d', 0);
        $data = [
            'name'        => inputs('name/s', ''),
            'api_key'     => inputs('api_key/s', ''),
            'api_secret'  => inputs('api_secret/s', ''),
            'endpoint'    => inputs('endpoint/s', ''),
            'priority'    => inputs('priority/d', 0),
            'daily_limit' => inputs('daily_limit/d', 0),
            'config'      => inputs('config/a', []),
        ];

        $api = TranslateApiModel::find($id);
        if (!$api) {
            $this->error('API配置不存在');
        }

        $api->save($data);
        $this->success('编辑成功');
    }

    /**
     * @notes 删除API配置
     * @auth true
     */
    public function deleteApi()
    {
        $id  = inputs('id/d', 0);
        $api = TranslateApiModel::find($id);

        if (!$api) {
            $this->error('API配置不存在');
        }

        $api->delete();
        $this->success('删除成功');
    }

    /**
     * @notes 启用/禁用API
     * @auth true
     */
    public function toggleApi()
    {
        $id  = inputs('id/d', 0);
        $api = TranslateApiModel::find($id);

        if (!$api) {
            $this->error('API配置不存在');
        }

        $api->is_enabled = $api->is_enabled ? 0 : 1;
        $api->save();

        $action = $api->is_enabled ? '启用' : '禁用';
        $this->success("{$action}成功");
    }

    /**
     * @notes 测试API连接
     * @auth true
     */
    public function testApi()
    {
        $id = inputs('id/d', 0);

        $translateApiService = new TranslateApiService();
        $result              = $translateApiService->testApiConnection($id);

        if ($result['success']) {
            $this->success($result['message'], $result);
        } else {
            $this->error($result['message']);
        }
    }

    /**
     * @notes 获取API使用统计
     * @auth true
     */
    public function getUsageStats()
    {
        $translateApiService = new TranslateApiService();
        $stats               = $translateApiService->getApiUsageStats();
        $this->success('', $stats);
    }

    /**
     * @notes 重置每日使用次数
     * @auth true
     */
    public function resetDailyUsage()
    {
        $id = inputs('id/d', 0);

        if ($id > 0) {
            $api = TranslateApiModel::find($id);
            if (!$api) {
                $this->error('API配置不存在');
            }
            $api->daily_used = 0;
            $api->save();
            $this->success('重置成功');
        } else {
            // 重置所有API的每日使用次数
            TranslateApiModel::resetDailyUsage();
            $this->success('批量重置成功');
        }
    }

    /**
     * @notes 获取提供商选项
     * @auth true
     */
    public function getProviderOptions()
    {
        $options = TranslateApiModel::getProviderOptions();
        $this->success('', $options);
    }

    /**
     * @notes 获取提供商默认配置
     * @auth true
     */
    public function getProviderDefaults()
    {
        $provider = inputs('provider/s', '');

        $defaults = [
            'baidu'  => [
                'endpoint'    => 'https://fanyi-api.baidu.com/api/trans/vip/translate',
                'daily_limit' => 1000000,
                'config'      => ['from' => 'zh', 'to' => 'en']
            ],
            'google' => [
                'endpoint'    => 'https://translation.googleapis.com/language/translate/v2',
                'daily_limit' => 500000,
                'config'      => ['format' => 'text']
            ],
            'deepl'  => [
                'endpoint'    => 'https://api-free.deepl.com/v2/translate',
                'daily_limit' => 500000,
                'config'      => ['formality' => 'default']
            ],
            'openai' => [
                'endpoint'    => 'https://api.openai.com/v1/chat/completions',
                'daily_limit' => 100000,
                'config'      => ['model' => 'gpt-3.5-turbo', 'temperature' => 0.3]
            ]
        ];

        $this->success('', $defaults[$provider] ?? []);
    }
}
